<template>
  <div class="content-list">
    <el-tabs v-model="curState" @tab-change="handleTabChange">
      <el-tab-pane v-for="item in tabArr" :key="item.state" :label="item.name + '(' + item.count + ')'" :name="item.state" />
    </el-tabs>
    <div class="header-top">
      <div class="left-btn">
        <div class="el-button-group">
          <el-button-group>
            <el-button v-permission="['content:manage:setting:add']" type="primary" @click="linkToAdd">{{ publishText }}</el-button>
            <el-dropdown>
              <el-button type="primary"><i class="iconfont">&#xe78d;</i></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item><el-button @click="handleConditionSort">排序</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button @click="handlePageSort">跨页暂存</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-button-group>
        </div>
        <SearchCmp ref="searchCmpRef" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData.likeParams" @onSubmit="handleSearch" />
      </div>
    </div>
    <!-- 表格样式 -->
    <ConditionSort v-model:show="showConditionSort" :orderFields="orderFields" :catId="catId" @sort="handleSearch" />
    <PageSort ref="pageSortRef" v-model:show="showPageSort" @handleClear="handleSearch" />
    <div class="ruifox-list">
      <RuifoxTable
        :key="catId"
        :loading="tableLoading"
        v-model:tableData="newTableData"
        v-model:fieldList="fieldList"
        :canDrag="hasPermission(['content:manage:setting:edit'])"
        :default-index="true"
        :default-checkbox="true"
        :default-colum-config="true"
        :tableProps="tableProps"
        @handleSearch="handleSearch"
        @handleSort="handleSort"
      >
        <!-- 多选 -->
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
          </div>
        </template>
        <!-- 置顶 -->
        <template #is_top='{element}'>
          <div class="table-td-top">
            <span v-permission="['content:manage:top']" :class="{'ding-yes': element.is_top,'ding-no': !element.is_top}" @click="handleTop(element)">顶</span>
          </div>
        </template>
        <!-- 锁定 -->
        <template #is_lock="{ element }">
          <el-tag type="danger" v-if="element.is_lock">已锁定</el-tag>
          <el-tag type="success" v-else>未锁定</el-tag>
        </template>
        <!-- 收藏 -->
        <template #is_collect="{ element }">
          <span :title="element.is_collect ? '取消收藏' : '收藏'" class="collect-btn" :class="{'is-collect': element.is_collect}" @click="handleCollect(element)">
            <i class="iconfont">&#xe68c;</i>
          </span>
        </template>
        <!-- 所属栏目 -->
        <template #cat_id="{ element }">
          <span>{{ element.category_name }}</span>
        </template>
        <!-- 发布用户 -->
        <template #publish_user_id="{ element }">
          <span>{{ element.publish_user_name }}</span>
        </template>
        <!-- 标题缩略图 -->
        <template #thumb="{ element }">
          <div class="table-td-title">
            <div class="title-box">
              <el-popover>
                <template #reference>
                  <div class="thumb-box" style="max-width: 42px;height: 24px;" v-show="element.thumb">
                    <img :src="element.thumb" alt="" style="max-width: 100%;max-height: 100%">
                  </div>
                </template>
                <template #default>
                  <div class="thumb-box" style="max-width: 150px;max-height: 300px">
                    <img :src="element.thumb" alt="" style="width: 100%;height: 100%">
                  </div>
                </template>
              </el-popover>
            </div>
          </div>
        </template>
        <!-- url -->
        <template #url="{ element }">
          <p v-html="element.url" :title="element.url"></p>
        </template>
        <!-- 状态 -->
        <template #state="{ element }">
          <el-tag type="success">{{ element.state_message }}</el-tag>
        </template>
        <!-- 操作 -->
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button v-if="hasPermission(['content:manage:setting:edit']) && [99,1,3].includes(curState)" type="primary" link @click="handleEdit(element)" :disabled="!element.is_lock ? false : true">编辑</el-button>
            <el-button v-if="hasPermission(['content:manage:revoke']) && [99].includes(curState)" type="primary" link @click="handleRevoke(element)" :disabled="!element.is_lock ? false : true">撤稿</el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="iconfont">&#xe78d;</i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="hasPermission(['content:manage:push']) && [99].includes(curState)" @click="handlePush(element)">投递</el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:lock']) && [99, 0, 1, 2, 3, 4].includes(curState)" @click="handleLock(element)">
                      {{ element.is_lock? '解锁' : '上锁' }}
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:top']) && [99, 0, 1, 2, 3, 4].includes(curState)" @click="handleTop(element)">
                      {{ element.is_top? '取消置顶' : '置顶' }}
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:revoke']) && [2].includes(curState)" @click="handleRecover(element)">恢复</el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:setting:preview']) && true" @click="handleViewFront(element)">前台浏览</el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:archive']) && [99, 0, 1, 2, 3].includes(curState)" @click="handleArchive(element)">手动归档</el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:move']) && [99].includes(curState)" @click="handleMove(element)">移动</el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:copy']) && [99].includes(curState)" @click="handleCopy(element)">复制</el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission(['content:manage:delete']) && [4].includes(curState)" @click="handleDelete(element)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </RuifoxTable>
    </div>
    <PaginationView
      :total="queryData.total"
      :pageSize="queryData.pageSize"
      :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn"
      :pageChoose="isPageChooseBtn"
      :checkedNum="checkedNum"
      :options="curStateOptions"
      @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose"
      @changeAllChoose="handleAllChoose"
      @cancelChoose="handleResetPagination"
      @invertChoose="handleInvertChoose"
      @refreshList="getTableData"
      @checkOption="handleBatch"
    />
    <!-- 栏目选择弹框 -->
    <DialogTree v-model:showDialog="showChooseCategory" :categoryList="pushCategoryList" :isSingle="isSingle" @treeChoose="submitCategory"></DialogTree>
  </div>
</template>

<script setup>
/* eslint-disable */ 
import { ref, reactive, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getContentPage, getContentStatistics, updateSystemData, moveContent, batchMoveContent, batchCopyContent, batchUpdateSystemData, collectContent, batchCollectContent, copyContent, checkPreview, updateSort, deleteContent } from '@/api/content'
import { getModelList, getFieldList } from '@/api/model'
import { getCategoryByModelId } from '@/api/category'
import { tableList as mixTable, createTreeData, hasPermission } from '@ruifox-cms/utils'
import { getSiteGroup } from '@/utils/storage'
import PageSort from './components/PageSort.vue'
import ConditionSort from './components/ConditionSort.vue'


const router = useRouter()
const store = useStore()
// 分页逻辑局部混入
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllSearch,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: getContentPage
})
// 通用列表组件，catId变，重新搜索内容
const catId = computed(() => Number(router.currentRoute.value.query.catId))
const modelId = computed(() => Number(router.currentRoute.value.query.modelId))
const searchCmpRef = ref(null)
watch(
  () => catId.value,
  newVal => {
    searchCmpRef.value?.clearForm(queryData)
    searchCmpRef.value?.showTags()
    Object.assign(queryData, defaultQueryData)
    queryData.catId = newVal
    queryData.currentPage = 1
    queryData.state = 99
    curState.value = 99
    if (newVal) {
      handleResetPagination()
      _getFieldList()
      _getContentStatistics()
      getTableData()
      showPageSort.value = false
      pageSortRef.value.tableData = []
    }
  }
)
// tableData排除显示暂存区的内容
const newTableData = ref([])
watch(tableData, newVal => {
  if (showPageSort.value) {
    const sortIds = pageSortRef.value.tableData.map(item => item.id)
    newTableData.value = structuredClone(newVal)
    newTableData.value = newTableData.value.filter(item => !sortIds.includes(item.id))
  } else {
    newTableData.value = structuredClone(newVal)
  }
}, { deep: true })
// 获取当前模型信息
const modelList = ref([])
const _getModelList = async () => {
  const res = await getModelList()
  if (res.code === 20000) {
    modelList.value = res.data
  }
}
const curModel = computed(() => modelList.value.find(item => item.id == modelId.value))
const publishText = computed(() => {
  if (curModel.value) {
    return '发布' + curModel.value.name
  } else {
    return '发布'
  }
})
// 顶部tab及各状态可操作选项（注意添加state不要重复）
const curState = ref(99)
const curStateOptions = computed(() => {
  let result = []
  const options = tabArr.find(item => item.state == curState.value)?.options || []
  if(options.length > 0) {
    options.forEach(item => {
      if(!item.permission || hasPermission([item.permission])){
        result.push(item)
      }
    })
  }
  return result
})
const tabArr = reactive([
  {
    state: 99,
    name: '已发布',
    count: 0,
    options: [ // 批量操作
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: 'content:manage:top'},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: 'content:manage:top'},
      {name: '收藏', icon: '&#xe6f4;', value: 'batchCollect', permission: ''},
      {name: '取消收藏', icon: '&#xe6f3;', value: 'batchCancelCollect', permission: ''},
      {name: '上锁', icon: '&#xe6e0;', value: 'batchLock', permission: 'content:manage:lock'},
      {name: '解锁', icon: '&#xe6df;', value: 'batchCancelLock', permission: 'content:manage:lock'},
      {name: '撤稿', icon: '&#xe6e8;', value: 'batchRevoke', permission: 'content:manage:revoke'},
      {name: '归档', icon: '&#xe709;', value: 'batchArchive', permission: 'content:manage:archive'},
      {name: '移动', icon: '&#xe6eb;', value: 'batchMove', permission: 'content:manage:move'},
      {name: '复制', icon: '&#xe6ed;', value: 'batchCopy', permission: 'content:manage:copy'}
    ]
  },
  {
    state: 0,
    name: '审核中',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: 'content:manage:top'},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: 'content:manage:top'},
      {name: '收藏', icon: '&#xe6f4;', value: 'batchCollect', permission: ''},
      {name: '取消收藏', icon: '&#xe6f3;', value: 'batchCancelCollect', permission: ''},
      {name: '上锁', icon: '&#xe6e0;', value: 'batchLock', permission: 'content:manage:lock'},
      {name: '解锁', icon: '&#xe6df;', value: 'batchCancelLock', permission: 'content:manage:lock'}
    ]
  },
  {
    state: 1,
    name: '草稿箱',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: 'content:manage:top'},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: 'content:manage:top'},
      {name: '收藏', icon: '&#xe6f4;', value: 'batchCollect', permission: ''},
      {name: '取消收藏', icon: '&#xe6f3;', value: 'batchCancelCollect', permission: ''},
      {name: '上锁', icon: '&#xe6e0;', value: 'batchLock', permission: 'content:manage:lock'},
      {name: '解锁', icon: '&#xe6df;', value: 'batchCancelLock', permission: 'content:manage:lock'}
    ]
  },
  {
    state: 2,
    name: '撤稿箱',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: 'content:manage:top'},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: 'content:manage:top'},
      {name: '收藏', icon: '&#xe6f4;', value: 'batchCollect', permission: ''},
      {name: '取消收藏', icon: '&#xe6f3;', value: 'batchCancelCollect', permission: ''},
      {name: '上锁', icon: '&#xe6e0;', value: 'batchLock', permission: 'content:manage:lock'},
      {name: '解锁', icon: '&#xe6df;', value: 'batchCancelLock', permission: 'content:manage:lock'},
      {name: '恢复', icon: '&#xe67b;', value: 'batchRecover', permission: 'content:manage:revoke'}
    ]
  },
  {
    state: 3,
    name: '已退稿',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: 'content:manage:top'},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: 'content:manage:top'},
      {name: '收藏', icon: '&#xe6f4;', value: 'batchCollect', permission: ''},
      {name: '取消收藏', icon: '&#xe6f3;', value: 'batchCancelCollect', permission: ''},
      {name: '上锁', icon: '&#xe6e0;', value: 'batchLock', permission: 'content:manage:lock'},
      {name: '解锁', icon: '&#xe6df;', value: 'batchCancelLock', permission: 'content:manage:lock'}
    ]
  },
  {
    state: 4,
    name: '已归档',
    count: 0,
    options: [
      {name: '置顶', icon: '&#xe6f2;', value: 'batchTop', permission: 'content:manage:top'},
      {name: '取消置顶', icon: '&#xe6f1;', value: 'batchCancelTop', permission: 'content:manage:top'},
      {name: '收藏', icon: '&#xe6f4;', value: 'batchCollect', permission: ''},
      {name: '取消收藏', icon: '&#xe6f3;', value: 'batchCancelCollect', permission: ''},
      {name: '上锁', icon: '&#xe6e0;', value: 'batchLock', permission: 'content:manage:lock'},
      {name: '解锁', icon: '&#xe6df;', value: 'batchCancelLock', permission: 'content:manage:lock'}
    ]
  }
])
const _getContentStatistics = async () => {
  const res = await getContentStatistics({ catId: catId.value })
  if (res.code === 20000) {
    tabArr.forEach(item => {
      item.count = res.data[item.state] || 0
    })
  }
}
_getContentStatistics()
const handleTabChange = val => {
  queryData.state = val
  handleResetPagination()
  getTableData()
}
watch(
  curState,
  newVal => {
    queryData.state = newVal
  },
  { deep: true, immediate: true }
)

// 条件排序
const showConditionSort = ref(false)
const handleConditionSort = () => {
  showConditionSort.value = true
}

// 跨页暂存
const showPageSort = ref(false)
const pageSortRef = ref(null)
const handlePageSort = () => {
  if (showPageSort.value && pageSortRef.value.tableData.length > 0) {
    ElMessageBox.confirm(
      '当前暂存区还有内容，关闭后将还原内容到列表，是否继续？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      showPageSort.value = !showPageSort.value
      pageSortRef.value.tableData = []
      handleSearch()
    })
  } else {
    showPageSort.value = !showPageSort.value
  }
}

// 表头数据处理
const fieldList = ref([])
const orderFields = ref([]) // 排序字段
const tableProps = reactive({
  labelKey: 'name',
  valueKey: 'field'
})
const _getFieldList = async () => {
  tableLoading.value = true
  fieldList.value = []
  let res = await getFieldList({ modelId: curModel.value.id, enable: true })
  if (res.code === 20000) {
    orderFields.value = res.data.filter(item => item.isOrder)
    res.data.forEach(item => {
      if (item.isShowControl || item.isShow) {
        item.show = item.isShow
        // 特殊处理字段
        switch(item.field) {
          case 'title':
            item.showTextTip = true
            item.width = 450
            item.fixed = 'left'
            break
          case 'is_top':
            item.width = 30
            item.hideTitle = true
            item.fixed = 'left'
            break
          // case 'thumb':
          //   item.width = 30
          //   item.hideTitle = true
          //   item.fixed = 'left'
          //   break
          case 'url':
            item.showTipText = true
            item.width = 250
            break
          case 'create_time':
            item.width = 150
            break
          case 'publish_time':
            item.width = 150
            break
        }
        // 字段选项禁用处理
        if (item.isShow && !item.isShowControl) {
          item.default = true
        }
        fieldList.value.push(item)
      }
    })
    fieldList.value.push({ name: '操作', field: 'options', width: 150, fixed: 'right', showToUser: false })
    // 前三个字段一定是标题、置顶状态、收藏状态（收藏状态手动加，标题和置顶找到后移动到前面来）
    const titleIndex = fieldList.value.findIndex(item => item.field === 'title')
    const topIndex = fieldList.value.findIndex(item => item.field === 'is_top')
    if (titleIndex !== -1) {
      fieldList.value.splice(0, 0, fieldList.value.splice(titleIndex, 1)[0])
    }
    if (topIndex !== -1) {
      fieldList.value.splice(1, 0, fieldList.value.splice(topIndex, 1)[0])
    }
    fieldList.value.splice(1, 0, { name: '', field: 'is_collect', width: 30, fixed: 'left', showToUser: false })
    handleDealSearchCmpArray()
  }
  tableLoading.value = false
}
// 可查询字段
const searchCmpArray = ref([])
const handleDealSearchCmpArray = () => {
  searchCmpArray.value = []
  fieldList.value.forEach(item => {
    if (item.isSearch) {
      let fieldObj = {
        key: item.field,
        label: item.name
      }
      fieldObj.form_type = fieldTypeMap[item.component]
      if (item.setting.options) {
        fieldObj.options = item.setting.options
      }

      searchCmpArray.value.push(fieldObj)
    }
  })
}
// 字段类型map
const fieldTypeMap = reactive({
  text: '',
  textarea: '',
  checkbox: 'multiple',
  select: 'select',
  selectMultiple: 'multiple',
  radio: 'select',
  datetime: 'datetime',
  number: 'count',
  title: '',
  summary: '',
  editor: '',
  depart: 'depart',
  category: 'category'
})
// 内容列表查询参数
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  catId: '',
  likeParams: {},
  equalParams: {}
})
Object.assign(queryData, defaultQueryData)
/*************************************************************行操作*************************************/
// 收藏内容
const handleCollect = async (data) => {
  const obj = {
    catId: catId.value,
    id: data.id,
    isCollect: !data.is_collect
  }
  const res = await collectContent(obj)
  if(res.code === 20000){
    const msg = obj.isCollect? '收藏成功' : '取消收藏成功'
    ElMessage.success(msg)
    getTableData()
  }
}

// 编辑内容
const handleEdit = data => {
  const toUrl = router.resolve({
    path: '/content/manage/setting',
    query: {
      modelId: modelId.value,
      catId: catId.value,
      publishType: curModel.value.publishType,
      dataId: data.data_id
    }
  })
  window.open(toUrl.href, '_blank')
}

// 撤稿
const handleRevoke = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否将选中内容移动到撤稿箱？</p><span style="font-size: 14px;color: #FF5240;">撤稿后前台将不展示选中内容</span></div>', '撤稿确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const obj = {
      catId: catId.value,
      id: data.id,
      state: 2
    }
    updateSystemData(obj).then(res => {
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: '撤稿成功',
          type: 'success'
        })
      }
      getTableData()
      _getContentStatistics()
    })
  })
}

// 拖拽排序
const handleSort = async (e) => {
  // 如果拖拽到了PageSort组件，则不触发排序
  if (e.to.className.includes('page-sort-list')) {
    return
  }

  let startSourceId, endSourceId, targetId
  const movedContent = newTableData.value[e.newIndex]
  // 如果是移动到最前面，或者目标位置前一条内容为置顶内容,且自身不是置顶内容时，则targetId为0
  const previousIndex = e.newIndex - 1
  if(previousIndex >= 0 && (!newTableData.value[previousIndex].is_top || (newTableData.value[previousIndex].is_top && movedContent.is_top))){
    const previousContent = newTableData.value[previousIndex]
    targetId = previousContent.id
  } else {
    targetId = 0
  }
  // 如果是批量移动，则取最小和最大排序值所对应元素的id
  if (movedContent.isPageSort) {
    startSourceId = Math.min(...movedContent.content.map(item => item.id))
    endSourceId = Math.max(...movedContent.content.map(item => item.id))
    // 然后展开数组插入到tableData中
    newTableData.value.splice(e.newIndex, 1, ...movedContent.content)
    pageSortRef.value.tableData = []
  } else {
    startSourceId = movedContent.id
    endSourceId = movedContent.id
  }
  const data = {
    catId: catId.value,
    startSourceId,
    endSourceId,
    targetId
  }
  await updateSort(data)
  handleSearch()
}

// 上锁解锁
const handleLock = data => {
  const obj = {
    catId: catId.value,
    id: data.id,
    isLock: data.is_lock ? 0 : 1
  }
  updateSystemData(obj).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: data.isLock ? '解锁成功' : '上锁成功',
        type: 'success'
      })
    }
    getTableData()
  })
}

// 置顶取消置顶
const handleTop = data => {
  const obj = {
    catId: catId.value,
    id: data.id,
    isTop: data.is_top ? 0 : 1
  }
  updateSystemData(obj).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: data.isTop ? '取消置顶成功' : '置顶成功',
        type: 'success'
      })
    }
    getTableData()
  })
}

// 恢复撤稿
const handleRecover = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否恢复该内容？</p></div>', '恢复确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const obj = {
      catId: catId.value,
      id: data.id,
      state: 99
    }
    updateSystemData(obj).then(res => {
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: '恢复成功',
          type: 'success'
        })
      }
      getTableData()
      _getContentStatistics()
    })
  })
}

// 前台浏览
const handleViewFront = data => {
  if (data.url) {
    // 已发布就直接访问前台地址
    window.open(data.url, '_blank')
  } else {
    // 无url则实时渲染
    let obj = {
      catId: store.state.content.currentCategory.id,
      dataContent: data
    }
    checkPreview(obj).then((res) => {
      const htmlContent = res.data
      const blob = new Blob([htmlContent], { type: "text/html" })
      const url = URL.createObjectURL(blob)
      let toUrl = router.resolve({
        path: "/content/manage/preview",
        query: { url }
      })
      window.open(toUrl.href, "_blank")
    })
  }
}

// 手动归档
const handleArchive = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否归档所选稿件</p></div>', '归档确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const obj = {
      catId: catId.value,
      id: data.id,
      state: 4
    }
    updateSystemData(obj).then(res => {
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: '归档成功',
          type: 'success'
        })
      }
      getTableData()
      _getContentStatistics()
    })
  })
}

// 投递
const showChooseCategory = ref(false)
const pushCategoryList = ref([])
const isSingle = ref(false) // 是否单选（打开dialogTree时，如果是移动内容，就只能单选）
const submitType = ref(null)

const handlePush = async () => {
  ElMessage.warning('暂未开放，请使用复制功能投递该内容到其他栏目')
}

// 移动
const moveData = reactive({})
const handleMove = async data => {
  await handleGetCategory()
  moveData.id = data.id
  moveData.originCatId = data.cat_id
  submitType.value = 'move'
  isSingle.value = true
  showChooseCategory.value = true
}

// 复制
const copyData = reactive({})
const handleCopy = async data => {
  await handleGetCategory([])
  copyData.id = data.id
  copyData.originCatId = data.cat_id
  submitType.value = 'copy'
  isSingle.value = false
  showChooseCategory.value = true
}

// 移动和复制操作 公用方法
const handleGetCategory = async () => {
  const res = await getCategoryByModelId({ modelId: curModel.value.id })
  if (res.code === 20000) {
    // 移动和复制时，不能选择当前栏目
    const index = res.data.findIndex(item => item.id === catId.value)
    if (index !== -1) {
      res.data.splice(index, 1)
    }
    const list = createTreeData(res.data)
    pushCategoryList.value = getSiteGroup()?.map(item => {
      return {
        name: item.name,
        id: item.id
      }
    })
    pushCategoryList.value.forEach(item => {
      item.children = []
      list.forEach(item2 => {
        if (item2.siteId === item.id) {
          item.children.push(item2)
        }
      })
    })
  }
}

// 提交选定栏目（投递、移动、复制）
const submitCategory = async data => {
  if (submitType.value === 'push') {
    // 投递
  } else if (submitType.value === 'move') {
    // 移动
    moveData.targetCatId = data[0].id
    const res = await moveContent(moveData)
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: '移动成功',
        type: 'success'
      })
    }
  } else if (submitType.value === 'copy') {
    // 复制
    copyData.targetCatIds = data.map(item => item.id)
    const res = await copyContent(copyData)
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: '复制成功',
        type: 'success'
      })
    }
  }else if (submitType.value === 'batchMove') {
    // 批量移动
    batchMoveData.ids = checkedList.value
    batchMoveData.targetCatId = data[0].id
    batchMoveData.isAllChoose = isAllSearch.value
    batchMoveData.state = queryData.state
    // 从queryData中取出支持搜索的字段，即searchCmpArray中支持的字段
    const searchFields = searchCmpArray.value.map(item => item.key)
    const params = {}
    searchFields.forEach(item => {
      params[item] = queryData[item]
    })
    batchMoveData.params = params
    const res = await batchMoveContent(batchMoveData)
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: '移动成功',
        type:'success'
      })
    }
  }else if (submitType.value === 'batchCopy') {
    // 批量复制
    batchCopyData.ids = checkedList.value
    batchCopyData.targetCatIds = data.map(item => item.id)
    batchCopyData.isAllChoose = isAllSearch.value
    batchCopyData.state = queryData.state
    const searchFields = searchCmpArray.value.map(item => item.key)
    const params = {}
    searchFields.forEach(item => {
      params[item] = queryData[item]
    })
    batchCopyData.params = params
    const res = await batchCopyContent(batchCopyData)
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: '复制成功',
        type:'success'
      })
    }
  }
  showChooseCategory.value = false
  handleResetPagination()
  getTableData()
  _getContentStatistics()
}

// 删除
const handleDelete = async data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除该内容？</p><span style="font-size: 14px;color: #FF5240;">清除后内容将无法恢复</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const res = await deleteContent({catId: catId.value, id: data.id})
    if (res.code === 20000) {
      ElMessage.success('删除成功')
      getTableData()
      _getContentStatistics()
    }
  })
}

/***************************************************************批量操作**********************************/
const handleBatch = async (val) => {
  switch (val) {
    case 'batchMove':
      handleBatchMove()
      break
    case'batchCopy':
      handleBatchCopy()
      break
    case 'batchCollect':
      handleBatchCollect(true)
      break
    case 'batchCancelCollect':
      handleBatchCollect(false)
      break
    case 'batchArchive':
      handleBatchSysField('targetState', 4)
      break
    case 'batchRevoke':
      handleBatchSysField('targetState', 2)
      break
    case 'batchRecover':
      handleBatchSysField('targetState', 99)
      break
    case 'batchTop':
      handleBatchSysField('isTop', 1)
      break
    case 'batchCancelTop':
      handleBatchSysField('isTop', 0)
      break
    case 'batchLock':
      handleBatchSysField('isLock', 1)
      break
    case 'batchCancelLock':
      handleBatchSysField('isLock', 0)
      break
  }
}
// 批量移动
const batchMoveData = reactive({})
const handleBatchMove = async () => {
  await handleGetCategory()
  batchMoveData.originCatId = catId.value
  submitType.value = 'batchMove'
  isSingle.value = true
  showChooseCategory.value = true
}

// 批量复制
const batchCopyData = reactive({})
const handleBatchCopy = async () => {
  await handleGetCategory()
  batchCopyData.originCatId = catId.value
  submitType.value = 'batchCopy'
  isSingle.value = false
  showChooseCategory.value = true
}

// 批量操作无需审核的字段（如是否上锁、是否置顶、撤稿归档等）
const handleBatchSysField = async (field, value) => {
  const searchFields = searchCmpArray.value.map(item => item.key)
  const params = {}
  searchFields.forEach(item => {
    params[item] = queryData[item]
  })
  const data = {
    catId: catId.value,
    [field]: value,
    ids: checkedList.value,
    isAllChoose: isAllSearch.value,
    originState: queryData.state,
    params
  }
  if(field === 'state'){
    const name = value === 4? '归档' : '撤稿'
    ElMessageBox.confirm(`<div><p style="font-size: 16px;margin-bottom: 15px;">是否${name}所选稿件</p></div>`, '归档确认', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(async () => {
      const res = await batchUpdateSystemData(data)
      if (res.code === 20000) {
        ElMessage.success('操作成功')
      }
      handleResetPagination()
      getTableData()
      _getContentStatistics()
    })
  }else{
    const res = await batchUpdateSystemData(data)
    if (res.code === 20000) {
      ElMessage.success('操作成功')
      handleResetPagination()
      getTableData()
      _getContentStatistics()
    }
  }
}

// 批量收藏或取消收藏
const handleBatchCollect = async (val) => {
  const searchFields = searchCmpArray.value.map(item => item.key)
  const params = {}
  searchFields.forEach(item => {
    params[item] = queryData[item]
  })
  const data = {
    catId: catId.value,
    ids: checkedList.value,
    isAllChoose: isAllSearch.value,
    isCollect: val,
    state: queryData.state,
    params
  }
  const res = await batchCollectContent(data)
  if (res.code === 20000) {
    ElMessage.success('操作成功')
    handleResetPagination()
    getTableData()
  }
}

// 发布内容
const linkToAdd = () => {
  const toUrl = router.resolve({
    path: '/content/manage/setting',
    query: {
      modelId: modelId.value,
      catId: catId.value,
      publishType: curModel.value.publishType
    }
  })
  window.open(toUrl.href, '_blank')
}

onMounted(async () => {
  await _getModelList()
  await _getFieldList()
  queryData.catId = catId.value
  getTableData()
  window['updatePage'] = val => {
    ElMessage({
      showClose: true,
      message: val,
      type: 'success'
    })
    getTableData()
    _getContentStatistics()
  }
})
onBeforeUnmount(() => {
  window['updatePage'] = null
})
</script>

<style lang="scss" scoped>
.content-list {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 5px rgba(#000, 0.1);
  width: 100%;
  margin-top: 15px;
  box-sizing: border-box;
  min-width: 650px;
  padding: 20px;
  .header-top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .left-btn {
      display: flex;
      .el-button-group {
        flex-shrink: 0;
        margin-right: 10px;
      }
    }
    .right-btn {
      display: flex;
      .change-card {
        height: 32px;
        width: 64px;
        box-sizing: border-box;
        border: var(--el-border);
        border-radius: 4px;
        display: flex;
        overflow: hidden;
        margin-left: 20px;

        a {
          display: flex;
          width: 50%;
          height: 100%;
          align-items: center;
          justify-content: center;
        }

        a.active {
          background-color: $mainColor;

          i {
            color: #fff;
          }
        }
      }
    }
  }
  .ruifox-card-options {
    .ruifox-card-btn {
      i {
        margin-right: 5px;
      }
    }
  }
  .ruifox-list {
    .collect-btn i {
      color: #ccc;
      cursor: pointer;
    }
    .collect-btn.is-collect i {
      color: $mainColor;
    }
    .table-td-top{
      width: 18px;
      min-width: 18px;
      .ding-yes{
        display: inline-block;
        width: 16px;
        height: 16px;
        font-size: 12px;
        color: $white;
        line-height: 16px;
        text-align: center;
        background-color: #FF5240;
        cursor: pointer;
        margin-right: 5px;
      }
      .ding-yes:hover{
        background-color: #f78a7e;
      }
      .ding-no{
        display: inline-block;
        cursor: pointer;
        width: 16px;
        height: 16px;
        font-size: 12px;
        color: $white;
        line-height: 16px;
        text-align: center;
        background-color: #D7D7D7;
        margin-right: 5px;
        visibility: hidden;
      }
      .ding-no:hover{
        background-color: #817f7f;
      }
    }
    .table-td-title{
      display: flex;
      align-items: center;
      .title-tips{
        .iconfont{
          font-size: 14px;
          color: $mainColor;
          margin-right: 3px;
        }
        span{
          color: #aaa;
          margin-right: 20px;
          position: relative;
        }
        span+span:before{
          content: '|';
          position: absolute;
          left: -10px;
          top: -8px;
        }
      }
      .title-box{
        display: flex;
        justify-content: center;
        align-items: center;
        p{
          @include textEllipsis(16px,1)
        }
        .iconimg{
          display: inline-block;
          width: 16px;
          margin-right: 5px;
          i{
            color: #2CBF77;
            font-size: 15px;
          }
        }
        .a-icon{
          display: inline-block;
          width: 16px;
          background-color: $mainColor;
          color: $white;
          line-height: 16px;
          text-align: center;
          i{
            font-size: 14px;
          }
        }
        .p-icon{
          display: flex;
          align-items: center;
          width: 20px;
          color: #2CBF77;
          i{
            font-size: 18px;
          }
        }
        .thumb-box {
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
.button-box {
  padding-right: 10px;
  .el-button + .el-button {
    margin-left: 0;
  }
  flex-grow: 0;
  position: relative;
  i {
    position: absolute;
    right: -13px;
    top: 5px;
    color: $mainColor;
    cursor: pointer;
  }
}
.libarary-table {
  width: 100%;
  ::v-deep(.el-table__cell) {
    height: 50px;
    padding: 4px 0;
  }
  .option-btn {
    width: 35px;
  }
}
</style>
